<template>
  <div class="bg-light">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link  class="text-dark" :to="`/politics/ai/practice?paperId=${examPaperId}&currentQuestionIndex=${currentQuestionIndex}`">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">答案解析</h5>
    </div>

    <!-- 解析内容 -->
    <div class="analysis-content">
      <div class="question-analysis">
        <div class="chapter-info">
          <i class="bi bi-bookmark-fill"></i>
          {{ currentQuestion.chapter }}
        </div>
        <div v-if="currentQuestion.article" class="question-text">
          {{ currentQuestion.article }}
        </div>
        <div v-for="text in this.currentQuestion.qtitles"  class="option-item">
            <div class="question-text">
              {{ text.textContent }}
            </div>
        </div>
        <div class="options-list">
          <div
            v-for="option in currentQuestion.options"
            :key="option.key"
            class="option-item"
            :class="{
              correct: this.currentQuestion.correctAnswer?this.currentQuestion.correctAnswer.includes(option.key):false,
              wrong: this.currentQuestion.userAnswer?this.currentQuestion.userAnswer.includes(option.key) &&!this.currentQuestion.correctAnswer.includes(option.key):false
            }"
          >
            <i
                :class="getOptionIcon(option.key)"
                v-if="this.currentQuestion.userAnswer && (this.currentQuestion.correctAnswer.includes(option.key) || this.currentQuestion.userAnswer.includes(option.key))"
            ></i>
            {{ option.key }}. {{ option.text }}
          </div>
        </div>
        <div v-if="this.currentQuestion.correctAnswer.length > 0" class="correct-answer">
          正确答案：{{ this.currentQuestion.correctAnswer.length > 0? this.currentQuestion.correctAnswer.join(", "):"" }}
        </div>
        <div class="analysis-detail">
          <!--          <p><strong>解析：</strong></p>-->
          <div class="sentence-analysis" :id="'analysis-ai'">
            <!-- 解析内容会动态插入到这里 -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/router/http';
import router from "@/router/index";
export default {
  name: 'PoliticsRealExplanationView',
  data() {
    return {
      selectedYear: 2024,
      examPaperId: null,
      currentQuestionIndex: null,
      currentQuestion: {
        article: null,
        chapter: '马克思主义基本原理 - 唯物辩证法',
        text: '关于唯物辩证法的基本规律，下列说法正确的是：',
        correctAnswer: [],
        userAnswer: [], // 假设用户选择了B
        qtitles: [],
        options: [
          { key: 'A', text: '对立统一规律是唯物辩证法的实质与核心' },
          { key: 'B', text: '量变质变规律揭示了事物发展的形式' },
          { key: 'C', text: '否定之否定规律体现了辩证发展观' },
          { key: 'D', text: '三大规律是平行并列的关系' }
        ],
        analysisIntro: '本题考查唯物辩证法的基本规律。',
        optionAnalysis: {
          'A': {
            isCorrect: true,
            explanation: '对立统一规律是唯物辩证法的实质和核心，它揭示了事物普遍联系的根本内容和变化发展的内在动力。'
          },
          'B': {
            isCorrect: false,
            explanation: '量变质变规律揭示的是事物发展的形式和状态。'
          },
          'C': {
            isCorrect: false,
            explanation: '否定之否定规律揭示的是事物发展的方向和道路。'
          },
          'D': {
            isCorrect: false,
            explanation: '三大规律不是平行并列关系，对立统一规律是最根本的规律。'
          }
        },
        analysis: {} // 新增用于存放后端返回的解析数据
      }
    }
  },
  created() {
    // 从路由参数获取年份和题号
    const year = parseInt(this.$route.query.year)
    const question = parseInt(this.$route.query.question)
    if (year) {
      this.selectedYear = year
    }
    if (question) {
      this.fetchQuestionData();
      this.analyzeQuestion();
    }
  },
  methods: {
    async fetchQuestionData() {
      http.get(`/student/question/getQuestionPoliticsInfoById?questionId=${this.$route.query.question}`)
          .then(response => {
            if (response.status === 200 && response.data && response.data.response) {
              this.currentQuestion = response.data.response;
              this.currentQuestion.options = [];
              this.currentQuestion.qtitles = [];
              if (response.data.response.childInfo && response.data.response.childInfo.length > 0) {
                const childItem = response.data.response.childInfo[0].item;
                if(childItem){
                  childItem.forEach(item => {
                    this.currentQuestion.options.push({
                      key: item.prefix,
                      text: item.content
                    })
                  })
                }
                this.currentQuestion.article = response.data.response.article;
                this.examPaperId = this.$route.query.examPaperId;
                this.currentQuestionIndex = this.$route.query.currentQuestionIndex;
                response.data.response.childInfo.forEach(item => {
                  this.currentQuestion.qtitles.push({
                    textContent: item.qtitle
                  })
                });
                let correctAnswerArray = response.data.response.correctAnswer? response.data.response.correctAnswer.split(",") : [];
                this.currentQuestion.correctAnswer = correctAnswerArray;
                if(this.$route.query.userAnswer){
                  let userAnswerArray = this.$route.query.userAnswer.split(",");
                  this.currentQuestion.userAnswer = userAnswerArray;
                }
              }
            }
          })
          .catch(error => {
            console.error('获取政治数据失败：', error);
            router.push('/politics');
          });
    },
    renderJsonValue(value) {
      if (value === null) return 'null';
      if (typeof value === 'undefined') return 'undefined';
      if (typeof value !== 'object') return value;

      return Object.entries(value).map(([key, val]) => `
          <div class="json-item">
            <span class="json-key">${key}:</span>
            <div class="json-value">
              ${Array.isArray(val)
          ? `<div class="json-array">
                    ${val.map(item =>
              `<div class="json-array-item">
                        ${typeof item === 'object' ? this.renderJsonValue(item) : item}
                      </div>`
          ).join('')}
                  </div>`
          : typeof val === 'object' && val !== null
              ? this.renderJsonValue(val)
              : `<span class="json-primitive">${val}</span>`
      }
            </div>
          </div>
        `).join('');
    },
    async analyzeQuestion() {
      http.get(`/student/topNalysis/analysticTopicForPolitics?questionId=${this.$route.query.question}&answer=${this.$route.query.wrongAnswer}`)
          .then(response => {
            if (response.status === 200 && response.data && response.data.response) {
              const data = response.data.response;
              // 解析返回的JSON字符串，获取其中的result字段内容并解析为对象
              // const analysisResult = JSON.parse(data.analysis);
              const analysisDataResult = JSON.parse(data.analysis);
              const analysisData = JSON.parse(analysisDataResult["result"]);
              // this.currentQuestion.analysis = analysisData["result"];
              const analysisDiv = document.getElementById('analysis-ai');
              if (analysisDiv) {
                // 清空之前可能存在的解析内容（避免多次点击重复添加）
                analysisDiv.innerHTML = '';
                Object.entries(analysisData).forEach(([key, value]) => {
                  const sectionDiv = document.createElement('div');
                  sectionDiv.classList.add('analysis-section');

                  const titleP = document.createElement('p');
                  titleP.innerHTML = `<strong>${key}</strong>`;

                  const valueDiv = document.createElement('div');
                  valueDiv.classList.add('analysis-value');
                  valueDiv.innerHTML = this.renderJsonValue(value);

                  sectionDiv.appendChild(titleP);
                  sectionDiv.appendChild(valueDiv);
                  analysisDiv.appendChild(sectionDiv);
                });
                analysisDiv.style.display = 'block';
                setTimeout(() => analysisDiv.classList.add('show'), 10);
              }
            }
          })
          .catch(error => {
            console.error('获取政治题目解析数据失败：', error);
            router.push('/politics');
          });
    },
    getOptionIcon(key) {
      let isCorrect = this.currentQuestion.correctAnswer.includes(key);
      let isWrong = this.currentQuestion.userAnswer.includes(key) &&!isCorrect;
      if (isCorrect) {
        return 'bi bi-check-circle-fill';
      }
      if (isWrong) {
        return 'bi bi-x-circle-fill';
      }
      return '';
    }
  }
}
</script>

<style>
.sentence-analysis {
  display: none;
  background: #f8f9fa;
  padding: 15px;
  margin: 10px 0;
  border-radius: 8px;
  border-left: 3px solid #40e0d0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.sentence-analysis.show {
  display: block;
  opacity: 1;
}

.analysis-section {
  margin: 15px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.analysis-section strong {
  color: #40e0d0;
  font-size: 1.1em;
}

.analysis-value {
  margin-top: 10px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}
.json-item {
  margin: 4px 0;
  padding-left: 16px;
}

.json-key {
  color: #0066cc;
  font-weight: 500;
}

.json-value {
  margin-left: 8px;
}

.json-array {
  margin-left: 16px;
}

.json-array-item {
  margin: 4px 0;
  padding-left: 8px;
  border-left: 2px solid #eee;
}

.json-primitive {
  color: #444;
}
.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.analysis-content {
  background: white;
  margin: 15px;
  padding: 20px;
  border-radius: 8px;
}

.question-analysis {
  margin-bottom: 30px;
}

.correct-answer {
  color: #28a745;
  font-weight: bold;
  margin: 10px 0;
}

.analysis-detail {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-top: 10px;
}

.key-points {
  color: #B19CD9;
  margin-top: 10px;
}

.chapter-info {
  color: #B19CD9;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.question-text {
  margin: 15px 0;
  color: #333;
}

.options-list {
  margin: 15px 0;
}

.option-item {
  padding: 8px;
  margin-bottom: 5px;
}

.option-item.correct {
  color: #28a745;
}

.option-item.wrong {
  color: #dc3545;
}

.option-item i {
  margin-right: 8px;
}

.analysis-item {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}

.analysis-item p {
  margin: 5px 0;
}

</style>